import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../core/constants/app_constants.dart';
import '../../core/routes/app_routes.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';

/// 底部导航栏组件
/// Bottom navigation bar widget for main app navigation
class BottomNavigationWidget extends StatefulWidget {
  /// 当前选中的索引
  /// Currently selected index
  final int currentIndex;

  /// 导航项点击回调
  /// Navigation item tap callback
  final Function(int index)? onTap;

  /// 是否显示标签
  /// Whether to show labels
  final bool showLabels;

  /// 导航项配置
  /// Navigation item configuration
  final List<BottomNavigationItem>? items;

  const BottomNavigationWidget({
    super.key,
    required this.currentIndex,
    this.onTap,
    this.showLabels = true,
    this.items,
  });

  @override
  State<BottomNavigationWidget> createState() => _BottomNavigationWidgetState();
}

class _BottomNavigationWidgetState extends State<BottomNavigationWidget>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late List<AnimationController> _itemControllers;
  late List<Animation<double>> _scaleAnimations;
  late List<Animation<Color?>> _colorAnimations;

  // 默认导航项配置
  // Default navigation items configuration
  static const List<BottomNavigationItem> _defaultItems = [
    BottomNavigationItem(
      icon: Icons.home_outlined,
      activeIcon: Icons.home,
      label: '首页',
      route: AppRoutes.home,
    ),
    BottomNavigationItem(
      icon: Icons.history_outlined,
      activeIcon: Icons.history,
      label: '历史',
      route: AppRoutes.history,
    ),
    BottomNavigationItem(
      icon: Icons.analytics_outlined,
      activeIcon: Icons.analytics,
      label: '分析',
      route: AppRoutes.analytics,
    ),
    BottomNavigationItem(
      icon: Icons.settings_outlined,
      activeIcon: Icons.settings,
      label: '设置',
      route: AppRoutes.settings,
    ),
  ];

  List<BottomNavigationItem> get _items => widget.items ?? _defaultItems;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  @override
  void dispose() {
    _animationController.dispose();
    for (final controller in _itemControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  /// 初始化动画
  /// Initialize animations
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    // 为每个导航项创建动画控制器
    // Create animation controllers for each navigation item
    _itemControllers = List.generate(
      _items.length,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 200),
        vsync: this,
      ),
    );

    // 创建缩放动画
    // Create scale animations
    _scaleAnimations = _itemControllers.map((controller) {
      return Tween<double>(
        begin: 1.0,
        end: 1.2,
      ).animate(CurvedAnimation(
        parent: controller,
        curve: Curves.elasticOut,
      ));
    }).toList();

    // 创建颜色动画
    // Create color animations
    _colorAnimations = _itemControllers.map((controller) {
      return ColorTween(
        begin: AppColors.textSecondary,
        end: AppColors.primary,
      ).animate(CurvedAnimation(
        parent: controller,
        curve: Curves.easeInOut,
      ));
    }).toList();

    // 启动入场动画
    // Start entrance animation
    _animationController.forward();

    // 激活当前选中项的动画
    // Activate animation for currently selected item
    if (widget.currentIndex < _itemControllers.length) {
      _itemControllers[widget.currentIndex].forward();
    }
  }

  @override
  void didUpdateWidget(BottomNavigationWidget oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 处理选中项变化
    // Handle selected item change
    if (oldWidget.currentIndex != widget.currentIndex) {
      _updateSelectedItem(oldWidget.currentIndex, widget.currentIndex);
    }
  }

  /// 更新选中项
  /// Update selected item
  void _updateSelectedItem(int oldIndex, int newIndex) {
    // 重置旧选中项动画
    // Reset old selected item animation
    if (oldIndex < _itemControllers.length) {
      _itemControllers[oldIndex].reverse();
    }

    // 激活新选中项动画
    // Activate new selected item animation
    if (newIndex < _itemControllers.length) {
      _itemControllers[newIndex].forward();
    }
  }

  /// 处理导航项点击
  /// Handle navigation item tap
  void _onItemTap(int index) {
    if (index == widget.currentIndex) return;

    // 触发自定义回调
    // Trigger custom callback
    if (widget.onTap != null) {
      widget.onTap!(index);
      return;
    }

    // 默认导航行为
    // Default navigation behavior
    final item = _items[index];
    if (item.route != null) {
      Get.offAllNamed(item.route!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.surfaceLight,
        boxShadow: [
          BoxShadow(
            color: AppColors.shadowColor,
            blurRadius: 8.r,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Container(
          // 调整高度以适配FloatingActionButton的centerDocked位置
          // Adjust height to accommodate FloatingActionButton's centerDocked position
          height: 85.h,
          padding: EdgeInsets.symmetric(
            horizontal: AppConstants.paddingMedium,
            vertical: 8.h,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: _items.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              final isSelected = index == widget.currentIndex;

              return _buildNavigationItem(
                item: item,
                index: index,
                isSelected: isSelected,
              );
            }).toList(),
          ),
        ),
      ),
    );
  }

  /// 构建导航项
  /// Build navigation item
  Widget _buildNavigationItem({
    required BottomNavigationItem item,
    required int index,
    required bool isSelected,
  }) {
    return Expanded(
      child: GestureDetector(
        onTap: () => _onItemTap(index),
        behavior: HitTestBehavior.opaque,
        child: AnimatedBuilder(
          animation: _itemControllers[index],
          builder: (context, child) {
            return Transform.scale(
              scale: _scaleAnimations[index].value,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  vertical: AppConstants.paddingSmall,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 图标容器
                    // Icon container
                    Container(
                      padding: EdgeInsets.all(4.w),
                      decoration: BoxDecoration(
                        color: isSelected
                            ? AppColors.primary.withOpacity(0.1)
                            : Colors.transparent,
                        borderRadius: BorderRadius.circular(6.r),
                      ),
                      child: Icon(
                        isSelected ? item.activeIcon : item.icon,
                        size: 20.w,
                        color: _colorAnimations[index].value,
                      ),
                    ),

                    if (widget.showLabels) ...[
                      SizedBox(height: 1.h),

                      // 标签
                      // Label
                      AnimatedDefaultTextStyle(
                        duration: const Duration(milliseconds: 200),
                        style: AppTextStyles.bodySmall.copyWith(
                          color: _colorAnimations[index].value,
                          fontWeight:
                              isSelected ? FontWeight.w600 : FontWeight.normal,
                          fontSize: 10.sp,
                        ),
                        child: Text(
                          item.label,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],

                    // 选中指示器
                    // Selected indicator
                    AnimatedContainer(
                      duration: const Duration(milliseconds: 200),
                      margin: EdgeInsets.only(top: 1.h),
                      height: 2.h,
                      width: isSelected ? 16.w : 0,
                      decoration: BoxDecoration(
                        color: AppColors.primary,
                        borderRadius: BorderRadius.circular(1),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

/// 底部导航项配置
/// Bottom navigation item configuration
class BottomNavigationItem {
  /// 未选中图标
  /// Unselected icon
  final IconData icon;

  /// 选中图标
  /// Selected icon
  final IconData activeIcon;

  /// 标签文字
  /// Label text
  final String label;

  /// 路由地址
  /// Route path
  final String? route;

  /// 点击回调
  /// Tap callback
  final VoidCallback? onTap;

  /// 徽章数量
  /// Badge count
  final int? badgeCount;

  /// 是否启用
  /// Whether enabled
  final bool enabled;

  const BottomNavigationItem({
    required this.icon,
    required this.activeIcon,
    required this.label,
    this.route,
    this.onTap,
    this.badgeCount,
    this.enabled = true,
  });
}

/// 自定义底部导航栏
/// Custom bottom navigation bar
class CustomBottomNavigationBar extends StatelessWidget {
  /// 当前选中的索引
  /// Currently selected index
  final int currentIndex;

  /// 导航项列表
  /// Navigation items list
  final List<BottomNavigationItem> items;

  /// 导航项点击回调
  /// Navigation item tap callback
  final Function(int index)? onTap;

  /// 背景颜色
  /// Background color
  final Color? backgroundColor;

  /// 选中颜色
  /// Selected color
  final Color? selectedItemColor;

  /// 未选中颜色
  /// Unselected color
  final Color? unselectedItemColor;

  /// 是否显示标签
  /// Whether to show labels
  final bool showLabels;

  /// 高度
  /// Height
  final double? height;

  const CustomBottomNavigationBar({
    super.key,
    required this.currentIndex,
    required this.items,
    this.onTap,
    this.backgroundColor,
    this.selectedItemColor,
    this.unselectedItemColor,
    this.showLabels = true,
    this.height,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      height: height ?? 70.h,
      decoration: BoxDecoration(
        color: backgroundColor ?? AppColors.surfaceLight,
        boxShadow: [
          BoxShadow(
            color: AppColors.shadowColor,
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Row(
          children: items.asMap().entries.map((entry) {
            final index = entry.key;
            final item = entry.value;
            final isSelected = index == currentIndex;

            return Expanded(
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: item.enabled ? () => onTap?.call(index) : null,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      vertical: 8.h,
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // 图标和徽章
                        // Icon and badge
                        Stack(
                          clipBehavior: Clip.none,
                          children: [
                            Icon(
                              isSelected ? item.activeIcon : item.icon,
                              size: 20.w,
                              color: isSelected
                                  ? (selectedItemColor ?? AppColors.primary)
                                  : (unselectedItemColor ??
                                      AppColors.textSecondary),
                            ),

                            // 徽章
                            // Badge
                            if (item.badgeCount != null && item.badgeCount! > 0)
                              Positioned(
                                right: -4.w,
                                top: -4.h,
                                child: Container(
                                  padding: EdgeInsets.all(1.w),
                                  decoration: BoxDecoration(
                                    color: AppColors.error,
                                    borderRadius: BorderRadius.circular(6.r),
                                  ),
                                  constraints: BoxConstraints(
                                    minWidth: 12.w,
                                    minHeight: 12.h,
                                  ),
                                  child: Text(
                                    item.badgeCount! > 99
                                        ? '99+'
                                        : '${item.badgeCount}',
                                    style: AppTextStyles.bodySmall.copyWith(
                                      color: Colors.white,
                                      fontSize: 8.sp,
                                      fontWeight: FontWeight.w600,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                ),
                              ),
                          ],
                        ),

                        if (showLabels) ...[
                          SizedBox(height: 2.h),

                          // 标签
                          // Label
                          Text(
                            item.label,
                            style: AppTextStyles.bodySmall.copyWith(
                              color: isSelected
                                  ? (selectedItemColor ?? AppColors.primary)
                                  : (unselectedItemColor ??
                                      AppColors.textSecondary),
                              fontWeight: isSelected
                                  ? FontWeight.w600
                                  : FontWeight.normal,
                              fontSize: 10.sp,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}
